package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private CacheClient cacheClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    public Shop queryWithPassThrough(Long id){
        String shopJSON = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id.toString());
        if(StrUtil.isNotBlank(shopJSON)){
            Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
            return shop;
        }

        if(shopJSON!=null){///此处，shopJSON为""
            return null;
        }
        //redis中没有缓存该店铺
        //去数据库查询
        Shop shop = getById(id);
        if(shop==null){
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }

        //店铺信息在数据库中存在
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id.toString(), JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);


        return shop;
    }

    public Shop queryWithLogicalExpire(Long id){/// 逻辑过期解决缓存穿透

        String redisDataJSON = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id.toString());
        if(redisDataJSON==null){
            return null;
        }

        RedisData redisData = JSONUtil.toBean(redisDataJSON, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject)redisData.getData(),Shop.class);

        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //如果没过期
            return shop;
        }

        boolean isLocked = tryLock("lock:shop:"+id);
        if(isLocked){

            try {
                executorService.submit(()-> this.saveShop2Redis(id,30L));
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unlock("lock:shop:"+id);
            }
        }
        return shop;

    }

    @Override
    public Result queryById(Long id) {

        Shop shop = cacheClient.getWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        Shop shop = queryWithMutex(id);

//        Shop shop = queryWithLogicalExpire(id);
        if(shop==null){
            return  Result.fail("店铺不存在");
        }
        return Result.ok(shop);

    }

    public Shop queryWithMutex(Long id){/// 互斥锁解决缓存穿透
        String shopJSON = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id.toString());
        if(StrUtil.isNotBlank(shopJSON)){
            Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
            return shop;
        }

        if(shopJSON!=null){///此处，shopJSON为""
            return null;
        }
        //redis中没有缓存该店铺

        Shop shop = null;
        try {
            boolean isLocked = tryLock("lock:shop:"+id);
            if(!isLocked){
                Thread.sleep(50);
                return queryWithMutex(id);
            }


            shop = getById(id);
            Thread.sleep(200);//模拟重建延时
            if(shop==null){
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }

            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id.toString(), JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock("lock:shop:"+id);
        }


        return shop;
    }


    public void saveShop2Redis(Long id ,Long expireSeconds){

        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }


    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("商户id为空");
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY+ id);
        return Result.ok();
    }

    private boolean tryLock(String lock){
        Boolean locked = stringRedisTemplate.opsForValue().setIfAbsent(lock, "locked", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(locked);
    }

    private void unlock(String lock){
        stringRedisTemplate.delete(lock);
    }

}
